import {Controller, BusinessError, ApiResponse} from "@codefree/badger/service";
import passport from 'passport'

import {createAuthToken} from "../utility/helper";

export default class Auth extends Controller {
    login() {
        const [req, res, next] = arguments;
        passport.authenticate('local', {session: false}, (err, user, info) => {
            if (err || !user) {
                res.send(ApiResponse.bizException(new BusinessError("用户名或密码错误")));
            } else {
                let token = createAuthToken(user, this.ctx.config.tokenExpire);
                res.set(this.ctx.config.authTokenName, token).send(ApiResponse.ok(user));
            }
        })(req, res, next);
    }

    async signUp() {
        const [req, res, next] = arguments;

        try {
            await this.service.auth.signUp(req.body);
            res.send(ApiResponse.ok());
        } catch (err) {
            next(err)
        }
    }
}